﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Business.Campaigns;
using iOak.Domain.Campaigns;
using iOak.Common;
using iOak.Common.Untity;
using iOak.Business.Resumes;
using iOak.Web.TemplateHelper;
using iOak.Core;
using System.IO;
using iOak.Domain.Resumes;
using iOak.Web.ExeclHelper;

namespace iOak.Web {
    public partial class CandidateList : BasePage {
        private static readonly ApplicationCandidateService itemApplicationCandidateService = new ApplicationCandidateService();
        private static readonly ResumeDetailService itemResumeDetailService = new ResumeDetailService();
        private static readonly ResumeService itemResumeService = new ResumeService();
        private static readonly CampaignService itemCampaignService = new CampaignService();
        private static readonly ResumeTemplateService itemResumeTemplateService = new ResumeTemplateService();
        private static readonly PolicyService itemPolicyService = new PolicyService();
        private static readonly ApplicationService itemApplicationService = new ApplicationService();
        private WorkAssistant _workassistant = new WorkAssistant();

        protected void Page_Load(object sender, EventArgs e) {
            if (!IsPostBack) {
                string campaignId = Request.QueryString["campaignId"];
                hidCampaignId.Value = campaignId;
                var itemApplication = itemApplicationService.GetListByCampaignIdAndCompanyId(new Guid(campaignId),
                    _workassistant.CurrentUser.CompanyId);

                if (itemApplication == null) {
                    // 创建
                    itemApplication = new ApplicationBase();
                    itemApplication.ApplicationId = Guid.NewGuid();
                    itemApplication.AppliedBy = _workassistant.CurrentUser.UserId;
                    itemApplication.AppliedDate = DateTime.Now;
                    itemApplication.CampaignId = new Guid(campaignId);
                    itemApplication.CompanyId = _workassistant.CurrentUser.CompanyId;
                    itemApplication.Status = (int)ApplicationStatus.Open;

                    itemApplicationService.Create(itemApplication);
                }
                Session["ApplicationId"] = itemApplication.ApplicationId;

                // 设定值
                var itemCampaign = itemCampaignService.Retrieve(new Guid(campaignId));
                var itemPolicy = itemPolicyService.Retrieve(itemCampaign.PolicyId);
                Guid resumeTemplateId = itemPolicy.ResumeTemplateId;
                hidResumeTemplateId.Value = resumeTemplateId.ToString();


                lblName.Text = itemCampaign.Subject;
                ltBotes.Text = itemCampaign.Description;
                ltTime.Text = itemApplication.AppliedDate.ToString("yyyy-MM-dd");

                //txtName.Text = itemCampaign.Subject;
                //txtBotes.Text = itemCampaign.Description;
                //txtTime.Text = itemApplication.AppliedDate.ToString("yyyy-MM-dd");

                htdGrid.BindData();
                //如果人才政策的状态是Checking 或 Closed，则不能再添加简历
                //if (itemCampaign.Status == (int)CampaignStatus.Checking || itemCampaign.Status == (int)CampaignStatus.Closed) {
                if (itemCampaign.Status == (int)CampaignStatus.Closed)
                {
                    btnAdd.Visible = false;
                    btnImport.Visible = false;
                }
            }
        }

        private List<ResumeField> GetNameList() {
            // 获取模板对象
            var listTemplate = TemplateCommonHelper.GetTemplateFileList(new Guid(hidResumeTemplateId.Value));

            return listTemplate;
        }

        protected void btnAdd_Click(object sender, EventArgs e) {
            Response.Redirect("ResumeEdit.aspx?campaignId=" + hidCampaignId.Value);
        }

        protected void btnExport_Click(object sender, EventArgs e) {
            var nameList = GetNameList().Where(m => m.Reqiured == true).OrderBy(m => m.ListNumber).Select(m => m.LabelText).ToList();

            string filePath = string.Empty;
            string fileName = string.Empty;
            ExportManager.ExportToExecl(nameList, out filePath, out fileName);

            CommonHelper.WriteResponseXls(filePath, fileName);

            if (File.Exists(filePath)) {
                File.Delete(filePath);
            }
        }

        protected void btnImport_Click(object sender, EventArgs e) {

            if (upfile.PostedFile != null && !String.IsNullOrEmpty(upfile.PostedFile.FileName)) {
                byte[] fileBytes = CommonHelper.StreamToBytes(upfile.PostedFile.InputStream);
                string extension = "xls";
                if (upfile.PostedFile.FileName.EndsWith("xlsx"))
                    extension = "xlsx";

                string fileName = string.Format("简历模板_{0}_{1}.{2}", DateTime.Now.ToString("yyyyMMddHHmmss"), CommonHelper.GenerateRandomDigitCode(4), extension);
                string filePath = string.Format("{0}files\\ExportImport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);

                File.WriteAllBytes(filePath, fileBytes);

                // 获取模板对象
                var listField = GetNameList();

                string strCheck = ImportManager.ImportCheck(filePath, listField);
                if (!string.IsNullOrWhiteSpace(strCheck)) {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "jAlert", "$(document).ready( function(){jAlert('" + strCheck + "')" + "});", true);
                    return;
                }

                ImportManager.ImportFromXls(filePath, new Guid(hidResumeTemplateId.Value), new Guid(Session["ApplicationId"].ToString()), listField);

                if (File.Exists(filePath)) {
                    File.Delete(filePath);
                }

                htdGrid.BindData();
            }
        }
    }
}
